import { userLoadingBar } from "@/hooks/userLoadingBar"
import { isEmpty } from "@/utils"
import type { RouteLocationNormalized, Router } from "vue-router"

/**
 * 创建导航守卫
 *
 * @param router 路由
 */
export function createRouterGuards(router: Router) {
    const loading = userLoadingBar()
    router.beforeEach(async to => {
        console.info("开始导航 => " + to.fullPath)
        // 开启进度条
        loading.start()
        // // 重定向
        // if (to.name === "Redirect") {
        //     return
        // }
        // // 不需要登录校验的，直接转向
        // const needLogin = determineNeedLogin(to)
        // if (!needLogin) {
        //     return
        // }
        // const token = useAccessToken()
        // const authStore = useAuthStore()
        // // 登录校验
        // if (isEmpty(token.value)) {
        //     authStore.logout()
        //     return { path: "login" }
        // }
        // if (authStore.isLogin) {
        //     return
        // }
        // await checkToken()
        // // 添加404
        // const isErrorPage = router.getRoutes().findIndex(item => item.name === "404")
        // if (isErrorPage === -1) {
        //     router.addRoute(NotFoundPageRoute)
        // }
        // return { path: to.path, replace: true }
    })

    router.afterEach(to => {
        setWindowsTitle(to)
        // addToKeepAliveQueue(to)
        loading.finish()
    })

    router.onError(error => {
        console.log(error, "路由错误")
    })
}

/**
 * 设置 router.meta.title 为标题
 */
const setWindowsTitle = (router: RouteLocationNormalized) => {
    const title = useTitle()
    let subTitle = router.meta.title
    let rootTitle = import.meta.env.VITE_APP_TITLE
    if (isEmpty(subTitle)) {
        title.value = rootTitle
    } else {
        title.value = subTitle + " - " + rootTitle
    }
}
